#include "TaskManager.h"

TaskManager::TaskManager(NetworkManager *manager):networkManager(manager)
{
    connect(networkManager,&NetworkManager::requestCompleted,this,&TaskManager::onRequestCompleted);
    connect(networkManager,&NetworkManager::networkError,this,&TaskManager::onNetworkError);
}

BatchCheckInResponse* TaskManager::BatchCheckIn(const QString& factoryNo,const QString& eventUser,const QString& machineNo,const QString& batch,const QList<BatchCheckInPcuInfo>& pcuInfo)
{
    BatchCheckInResponse*  responseBody = new BatchCheckInResponse();

    if(!pcuInfo.empty())
    {
        BatchCheckInRequest requestBody(
            factoryNo,
            QString("%1%2").arg(QDateTime::currentDateTime().toString("yyyyMMddhhmmssSSS")).arg(QRandomGenerator::global()->bounded(10000,100000)),
            QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"),
            eventUser,
            machineNo,
            batch,
            pcuInfo
            );

        int taskId = networkManager->sendRequest(requestBody,responseBody);
        networkTaskId[taskId] = checkIn;
        tasks.insert(checkIn,taskId);

        if(responseBody->resultCode=="0")
        {

        }
        else
        {
            QString msg = tr("任务[%1] (id: %2)失败").arg(checkIn).arg(taskId);
            qDebug()<<msg;
        }

    }
    return responseBody;
}

BatchCheckOutResponse* TaskManager::BatchCheckOut(const QString& factoryNo,const QString& eventUser,const QString& machineNo,const QString& batch,const QList<BatchCheckOutPcuInfo>& pcuInfo)
{
    BatchCheckOutResponse* responseBody = new BatchCheckOutResponse();

    if(!pcuInfo.empty())
    {
        BatchCheckOutRequest requestBody(
            factoryNo,
            QString("%1%2").arg(QDateTime::currentDateTime().toString("yyyyMMddhhmmssSSS")).arg(QRandomGenerator::global()->bounded(10000,100000)),
            QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"),
            eventUser,
            machineNo,
            batch,
            pcuInfo);
        qDebug()<<requestBody.toJson().toStdString();

        int taskId = networkManager->sendRequest(requestBody,responseBody);
        networkTaskId[taskId] = checkOut;
        tasks.insert(checkOut,taskId);

        if(responseBody->code == 0)
        {
            QString msg = tr("任务[%1] (id: %2)成功, 返回值[%2]").arg(checkOut).arg(taskId).arg(responseBody->code);
            qDebug()<<msg;
        }
        else
        {
            QString msg = tr("任务[%1] (id: %2)失败, 返回值[%2]").arg(checkOut).arg(taskId).arg(responseBody->code);
            qDebug()<<msg;
        }

    }

    return responseBody;
}

HeartbeatDetectionResponse* TaskManager::HeartbeatDetetion(const QString& factoryNo,const QString& eventUser,const QString& machineNo,const QString& status)
{
    HeartbeatDetectionResponse* responseBody = nullptr;

    HeartbeatDetectionRequest requestBody(
        factoryNo,
        QString("%1%2").arg(QDateTime::currentDateTime().toString("yyyyMMddhhmmssSSS")).arg(QRandomGenerator::global()->bounded(10000,100000)),
        QDateTime::currentDateTime(),
        eventUser,
        machineNo,
        status
        );

    auto response = new HeartbeatDetectionResponse();
    int taskId = networkManager->sendRequest(requestBody,response);
    networkTaskId[taskId]=heartbeatDetection;
    tasks.insert(heartbeatDetection,taskId);
    if(response->resultCode=="0")
    {
        responseBody = new HeartbeatDetectionResponse(response->factoryNo,response->transId,response->eventTime,response->resultCode,response->resultMsg);
    }
    else
    {
        QString msg = tr("任务[%1] (id: %2)失败, 返回值[%2]").arg(heartbeatDetection).arg(taskId).arg(response->resultCode);
        qDebug()<<msg;
    }
    return responseBody;
}

MatchProcParamCollectResponse* TaskManager::MatchProcParamCollectPost(const QString& factoryNo,const QString& eventUser,const QString& machineNo,const QList<ParamInfo>& paramInfo)
{
    MatchProcParamCollectResponse* responseBody = nullptr;
    if(!paramInfo.empty())
    {
        MatchProcParamCollectRequest requestBody(
            factoryNo,
            QString("%1%2").arg(QDateTime::currentDateTime().toString("yyyyMMddhhmmssSSS")).arg(QRandomGenerator::global()->bounded(10000,100000)),
            QDateTime::currentDateTime(),
            eventUser,
            machineNo,
            "NA","NA",
            paramInfo);
        const auto response = new MatchProcParamCollectResponse();
        int taskId = networkManager->sendRequest(requestBody,response);
        networkTaskId[taskId]=procParamCollect;
        tasks.insert(procParamCollect,taskId);

        if(response->resultCode == "0")
        {
            responseBody = new MatchProcParamCollectResponse();

            for(const auto& item:std::as_const(response->pcuInfo))
            {
                responseBody->pcuInfo.append({item.locationNo,item.pcu,item.resultMsg});
            }
            responseBody->factoryNo = response->factoryNo;
            responseBody->transId = response->transId;
            responseBody->eventTime = response->eventTime;
            responseBody->resultCode = response->resultCode;
        }
        else
        {
            QString msg = tr("任务[%1] (id: %l2)失败, 返回值[%2]").arg(procParamCollect).arg(taskId).arg(response->resultCode);
            qDebug()<<msg;
        }
    }
    return responseBody;
}

int TaskManager::TaskId(const QString &taskName)
{
    return tasks[taskName];
}


void TaskManager::onRequestCompleted(int taskId, bool success, const QString &error)
{
    //
    QString taskType = taskList.value(taskId, "Unknown");
    taskList.remove(taskId);

    if (success) {
        qDebug() << taskType << "request completed successfully";
    } else {
        qDebug() << taskType << "request failed:" << error;
    }

    emit onCurrentTaskCompleted();

}

void TaskManager::onNetworkError(int taskId, const QString &errorString)
{
    QString taskType = taskList.value(taskId, "Unknown");
    qDebug() << taskType << "network error:" << errorString;
    taskList.remove(taskId);
}
